from applications import create_app
from flask_migrate import Migrate
from applications.extensions import db
from flask import session, g, make_response
from applications.models import User
from flask_cors import *

app = create_app()

migrate = Migrate(app, db)

CORS(app, supports_credentials=True, resources=r"/*")


@app.before_request
def before_request():
    user_id = session.get("client_user_id")
    if user_id:
        try:
            user = User.query.get(user_id)
            g.client_user = user
        except:
            g.client_user = None


@app.context_processor
def context_processor():
    # 这个会在渲染视图函数前调用，如果当前已经有用户登录，那么该模板中会接收到一个不为None的user，反之
    if hasattr(g, "client_user"):
        # 返回一个字典给模板
        return {"client_user": g.client_user}
    else:
        return {}


if __name__ == '__main__':
    app.run()
